package com.hk.web.core.config.amqp;

import com.hk.base.constant.RabbitConstant;
import com.hk.commons.serializer.JacksonObjMapper;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableRabbit
public class RabbitConfig {

    @Bean
    public RabbitTemplate amqpTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter(new JacksonObjMapper()));
        rabbitTemplate.setAfterReceivePostProcessors();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        return rabbitTemplate;
    }

    /**
     * 主题交换机
     */
    @Bean
    public TopicExchange topicExchange(){
        return new TopicExchange(RabbitConstant.TOPIC_EXCHANGE_NAME);
    }

    /**
     * 发送消息队列
     */
    @Bean
    public Queue sendMsgQueue(){
        return new Queue(RabbitConstant.SEND_MEG_QUEUE);
    }

    //绑定队列到交换机
    @Bean
    public Binding bindingSendMsgQueue(){
        return BindingBuilder.bind(sendMsgQueue()).to(topicExchange()).with(RabbitConstant.SEND_MSG_ROUTING_KEY);
    }

}
